import sys,time
from qasync import QEventLoop, asyncSlot
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton
import asyncio
from tqsdk import TqApi, TqAuth, TqAccount, TqSim,TqKq
from PyQt5.QtGui import QIcon
from threading import Thread

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.api=None
        self.layout = QVBoxLayout()
        
        # 设置窗口图标
        self.setWindowIcon(QIcon(r'E:\Private.Net\WorkShop\tqsdk\Tq\App.png'))  # 请确保icon.png文件存在
        
        # 美化按钮样式
        button_style = """
            QPushButton {
                background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                                stop:0 #f8f9fa, stop:1 #e9ecef);
                border: 1px solid #ced4da;
                color: #212529;
                padding: 10px 24px;
                text-align: center;
                font-size: 14px;
                margin: 4px 2px;
                border-radius: 6px;
                border-bottom: 2px solid #adb5bd;
            }
            QPushButton:hover {
                background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                                stop:0 #e9ecef, stop:1 #dee2e6);
                border-color: #adb5bd;
            }
            QPushButton:pressed {
                background-color: #ffdddd;
                border-top: 1px solid #adb5bd;
                border-bottom: 1px solid #adb5bd;
                font-weight: bold;
            }
        """
        
        # 设置窗口背景色
        self.setStyleSheet("""
            background-color: #f8f9fa;
            font-family: 'Microsoft YaHei', sans-serif;
        """)
        self.button = QPushButton("连接天勤账户")
        self.button.setStyleSheet(button_style)
        self.button.clicked.connect(lambda: self.connect_tq())
        self.layout.addWidget(self.button)
        
        self.button2 = QPushButton("查询账户持仓")
        self.button2.setStyleSheet(button_style)
        self.button2.clicked.connect(lambda: self.my_position())
        self.layout.addWidget(self.button2)
        
        self.setLayout(self.layout)
        # 设置窗口背景色
        self.setStyleSheet("background-color: #f0f0f0;")

    @asyncSlot()
    async def connect_tq(self):
        """异步方法：连接天勤账户"""
        print("连接天勤账户...")
        tq_kq = TqKq()  # 创建快期模拟账户实例
        self.api = TqApi(account=tq_kq, auth=TqAuth("cps168", "alibaba999"))  # 使用账户和认证信息创建天勤API实例
        self.macc=self.api.get_account()  # 获取账户信息
        print("连接成功,账户可用资金为：",self.macc.available)  # 打印账户可用资金信息
    
    @asyncSlot()
    async def my_position(self):
        async def query_pos():
            """异步方法：查询账户持仓"""
            if self.api:
                print("查询账户持仓...")
                # 修改为查询所有持仓而不是特定合约
                positions = self.api.get_position()  # 获取所有持仓
                while True:
                    deadline = time.time() + 1
                    self.api.wait_update(deadline=deadline)
                    for symbol, pos in positions.items():
                        print(f"时间：{time.strftime('%Y-%m-%d %H:%M:%S')}",
                             f"{symbol} 持仓信息:", 
                             f"多头:{pos.pos_long}", 
                             f"空头:{pos.pos_short}")
        Thread(target=asyncio.run, args=(query_pos(),)).start()
    
    @asyncSlot()
    async def HelloWorld():
        print("Hello World!")

    def closeEvent(self, event):
        """重写关闭事件，关闭前检查并关闭天勤API"""
        if self.api is not None:
            print("正在关闭天勤API连接...")
            self.api.close()  # 关闭天勤API
        event.accept()  # 接受关闭事件
        
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.setWindowTitle("用协程操作天勤账户")
    window.resize(700, 600)
    window.show()
    # 创建 asyncio 事件循环并绑定到 Qt
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    sys.exit(app.exec())